<template>
  <div>
    <van-field v-model="data.currentDate" v-bind="$attrs" error-message-align="right" :is-link="$attrs.disabled === undefined || $attrs.disabled === false" readonly @click="showPopu($attrs.disabled as boolean)" />
    <van-popup v-model:show="data.showDate" round position="bottom">
      <van-date-picker ref="date" v-model="data.datetime" :min-date="minDate" :max-date="maxDate" :columns-type="type" @confirm="confirmDate" @cancel="data.showDate = false" />
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { parseTime, getType } from '@/utils'
//更新发送model
const emit = defineEmits(['confirm', 'update:modelValue'])
const props = defineProps({
  modelValue: {
    type: [String, Date, Number, Array],
    default: ''
  },
  minDate: {
    type: Date,
    default: () => {
      return new Date(1990, 0, 1)
    }
  },
  maxDate: {
    type: Date,
    default: () => {
      return new Date(2035, 12, 30)
    }
  },
  type: {
    type: Array<any>,
    default: ['year', 'month', 'day']
  },
  formatterLast: {
    type: String,
    default: '{y}/{m}/{d}'
  },
  modelFormatter: {
    type: String,
    default: '{y}/{m}/{d}'
  }
})
interface Config {
  showDate: boolean
  yearColumns: Array<any>
  currentDate: string
  datetime: Array<string>
}
const data: Config = reactive({
  showDate: false,
  yearColumns: [],
  currentDate: '', //label
  datetime: [] //所选
})

const showPopu = (disabled: boolean | undefined = false) => {
  // 显示隐藏
  if (disabled !== undefined && disabled !== false) {
    return false
  } else {
    data.showDate = !data.showDate
  }
}

const confirmDate = (val: any) => {
  // 确定
  data.showDate = false
  const Datestr = parseTime(val.selectedValues.join('/'), props.formatterLast) as string
  data.currentDate = Datestr
  emit('confirm', val, Datestr)
  //因为组件是默认数组格式，所以需要做兼容判断
  if (getType(props.modelValue) == 'Array') {
    emit('update:modelValue', val.selectedValues)
  } else {
    emit('update:modelValue', parseTime(val.selectedValues.join('/'), props.modelFormatter))
  }
}

//容错时间
const setTime = (val: any) => {
  data.currentDate = parseTime(val, props.formatterLast) as string
  let y = parseTime(val, '{y}')
  let m = parseTime(val, '{m}')
  let d = parseTime(val, '{d}')
  if (y) data.datetime.push(y)
  if (m) data.datetime.push(m)
  if (d) data.datetime.push(d)
}
//设置时间
watch(
  () => props.modelValue,
  newVal => {
    if (newVal) {
      if (getType(newVal) == 'Array') {
        //因为组件是默认数组格式，所以需要做兼容判断
        let val = newVal as Array<string>
        data.currentDate = parseTime(val.join('/'), props.formatterLast) as string
        data.datetime = val
      } else {
        setTime(newVal)
      }
    }
  },
  { immediate: true, deep: true }
)

//这里需要暴露出去不然父组件调用不到这个方法
defineExpose({
  showPopu
})
</script>
